package com.cyan.note.service.manager.impl;

import com.cyan.note.common.ApiResult;
import com.cyan.note.common.PageResult;
import com.cyan.note.common.ResultCode;
import com.cyan.note.dto.manager.customer.CustomerListDTO;
import com.cyan.note.dto.manager.customer.CustomerValidationDTO;
import com.cyan.note.entity.Customer;
import com.cyan.note.mapper.CustomerMapper;
import com.cyan.note.service.manager.ManagerCustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 店长端-客户管理服务实现类
 * 
 * @author ZhangzhenYu
 * @since 2025-01-15
 */
@Service
@Slf4j
public class ManagerCustomerServiceImpl implements ManagerCustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public ApiResult<PageResult<CustomerListDTO>> getCustomerList(Long shopId, Integer page, Integer size, 
            String keyword, String status, String level, String source, String registerStart, 
            String registerEnd, String minAmount, String maxAmount, String minOrders, 
            String maxOrders, String sortBy, String sortOrder) {
        
        try {
            // 参数转换
            List<String> statusList = StringUtils.hasText(status) ? Arrays.asList(status.split(",")) : null;
            List<String> levelList = StringUtils.hasText(level) ? Arrays.asList(level.split(",")) : null;
            
            LocalDateTime regStart = StringUtils.hasText(registerStart) ? 
                    LocalDateTime.parse(registerStart, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : null;
            LocalDateTime regEnd = StringUtils.hasText(registerEnd) ? 
                    LocalDateTime.parse(registerEnd, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : null;
            
            BigDecimal minAmountDecimal = StringUtils.hasText(minAmount) ? new BigDecimal(minAmount) : null;
            BigDecimal maxAmountDecimal = StringUtils.hasText(maxAmount) ? new BigDecimal(maxAmount) : null;
            Integer minOrdersInt = StringUtils.hasText(minOrders) ? Integer.parseInt(minOrders) : null;
            Integer maxOrdersInt = StringUtils.hasText(maxOrders) ? Integer.parseInt(maxOrders) : null;

            // 计算分页
            int offset = (page - 1) * size;

            // 查询数据
            List<Customer> customers = customerMapper.selectCustomerPage(shopId, keyword, statusList, 
                    levelList, regStart, regEnd, minAmountDecimal, maxAmountDecimal, 
                    minOrdersInt, maxOrdersInt, offset, size);

            // 查询总数
            int total = customerMapper.countCustomers(shopId, keyword, statusList, levelList, 
                    regStart, regEnd, minAmountDecimal, maxAmountDecimal, minOrdersInt, maxOrdersInt);

            // 转换为DTO
            List<CustomerListDTO> result = new ArrayList<>();
            for (Customer customer : customers) {
                CustomerListDTO dto = new CustomerListDTO();
                dto.setId(customer.getId());
                dto.setNickname(customer.getNickname());
                dto.setRealName(customer.getRealName());
                dto.setPhone(customer.getPhone());
                dto.setGender(customer.getGender());
                dto.setAvatar(customer.getAvatar());
                dto.setStatus(customer.getStatus());
                dto.setLevel(customer.getLevel());
                dto.setSource(customer.getSource());
                dto.setTotalConsumption(customer.getTotalConsumption());
                dto.setTotalOrders(customer.getTotalOrders());
                dto.setAccountBalance(customer.getAccountBalance());
                dto.setLastOrderTime(customer.getLastOrderTime());
                dto.setCreatedAt(customer.getCreatedAt());
                result.add(dto);
            }

            PageResult<CustomerListDTO> pageResult = PageResult.of(result, total, page, size);
            return ApiResult.success(pageResult);
        } catch (Exception e) {
            log.error("查询客户列表失败", e);
            return ApiResult.error(ResultCode.ERROR, "查询客户列表失败");
        }
    }

    @Override
    public ApiResult<Customer> getCustomerDetail(Long shopId, Long customerId) {
        try {
            Customer customer = customerMapper.selectById(customerId);
            if (customer == null || !customer.getShopId().equals(shopId)) {
                return ApiResult.error(ResultCode.NOT_FOUND, "客户不存在");
            }
            return ApiResult.success(customer);
        } catch (Exception e) {
            log.error("查询客户详情失败", e);
            return ApiResult.error(ResultCode.ERROR, "查询客户详情失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> createCustomer(Customer customer, Long operatorId) {
        try {
            // 检查昵称是否已存在
            Customer existingCustomer = customerMapper.selectByNicknameAndShopId(customer.getNickname(), customer.getShopId());
            if (existingCustomer != null) {
                return ApiResult.error(ResultCode.DUPLICATE_RESOURCE, "客户昵称已存在");
            }

            // 设置默认值
            customer.setStatus(Customer.Status.NORMAL);
            customer.setLevel(Customer.Level.NEW);
            customer.setAccountBalance(BigDecimal.ZERO);
            customer.setCreditLimit(BigDecimal.ZERO);
            customer.setTotalConsumption(BigDecimal.ZERO);
            customer.setTotalOrders(0);
            customer.setCreatedAt(LocalDateTime.now());
            customer.setUpdatedAt(LocalDateTime.now());

            int result = customerMapper.insert(customer);
            if (result > 0) {
                return ApiResult.success();
            } else {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "新增客户失败");
            }
        } catch (Exception e) {
            log.error("新增客户失败", e);
            return ApiResult.error(ResultCode.ERROR, "新增客户失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> updateCustomer(Customer customer, Long operatorId) {
        try {
            // 检查客户是否存在
            Customer existingCustomer = customerMapper.selectById(customer.getId());
            if (existingCustomer == null || !existingCustomer.getShopId().equals(customer.getShopId())) {
                return ApiResult.error(ResultCode.NOT_FOUND, "客户不存在");
            }

            // 检查昵称冲突
            Customer nicknameCheck = customerMapper.selectByNicknameAndShopId(customer.getNickname(), customer.getShopId());
            if (nicknameCheck != null && !nicknameCheck.getId().equals(customer.getId())) {
                return ApiResult.error(ResultCode.DUPLICATE_RESOURCE, "客户昵称已存在");
            }

            customer.setUpdatedAt(LocalDateTime.now());
            int result = customerMapper.updateById(customer);
            if (result > 0) {
                return ApiResult.success();
            } else {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "更新客户失败");
            }
        } catch (Exception e) {
            log.error("更新客户失败", e);
            return ApiResult.error(ResultCode.ERROR, "更新客户失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> deleteCustomer(Long shopId, Long customerId, Long operatorId) {
        try {
            // 检查客户是否存在
            Customer customer = customerMapper.selectById(customerId);
            if (customer == null || !customer.getShopId().equals(shopId)) {
                return ApiResult.error(ResultCode.NOT_FOUND, "客户不存在");
            }

            int result = customerMapper.deleteById(customerId);
            if (result > 0) {
                return ApiResult.success();
            } else {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "删除客户失败");
            }
        } catch (Exception e) {
            log.error("删除客户失败", e);
            return ApiResult.error(ResultCode.ERROR, "删除客户失败");
        }
    }

    @Override
    public ApiResult<CustomerValidationDTO> validateCustomer(Long shopId, String nickname) {
        try {
            Customer customer = customerMapper.selectByNicknameAndShopId(nickname, shopId);
            
            CustomerValidationDTO dto = new CustomerValidationDTO();
            if (customer != null) {
                dto.setExists(true);
                dto.setCustomerId(customer.getId());
                dto.setNickname(customer.getNickname());
                dto.setRealName(customer.getRealName());
                dto.setPhone(customer.getPhone());
                dto.setLevel(customer.getLevel());
                dto.setStatus(customer.getStatus());
                dto.setAccountBalance(customer.getAccountBalance());
                dto.setTotalOrders(customer.getTotalOrders());
                dto.setLastOrderTime(customer.getLastOrderTime());
            } else {
                dto.setExists(false);
                dto.setNickname(nickname);
            }

            return ApiResult.success(dto);
        } catch (Exception e) {
            log.error("客户校验失败", e);
            return ApiResult.error(ResultCode.ERROR, "客户校验失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> updateCustomerStatus(Long shopId, Long customerId, String status, Long operatorId) {
        try {
            Customer customer = customerMapper.selectById(customerId);
            if (customer == null || !customer.getShopId().equals(shopId)) {
                return ApiResult.error(ResultCode.NOT_FOUND, "客户不存在");
            }

            customer.setStatus(status);
            customer.setUpdatedAt(LocalDateTime.now());
            
            int result = customerMapper.updateById(customer);
            if (result > 0) {
                return ApiResult.success();
            } else {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "更新客户状态失败");
            }
        } catch (Exception e) {
            log.error("更新客户状态失败", e);
            return ApiResult.error(ResultCode.ERROR, "更新客户状态失败");
        }
    }

    @Override
    @Transactional
    public ApiResult<Void> updateCustomerLevel(Long shopId, Long customerId, String level, Long operatorId) {
        try {
            Customer customer = customerMapper.selectById(customerId);
            if (customer == null || !customer.getShopId().equals(shopId)) {
                return ApiResult.error(ResultCode.NOT_FOUND, "客户不存在");
            }

            customer.setLevel(level);
            customer.setUpdatedAt(LocalDateTime.now());
            
            int result = customerMapper.updateById(customer);
            if (result > 0) {
                return ApiResult.success();
            } else {
                return ApiResult.error(ResultCode.OPERATION_FAILED, "更新客户等级失败");
            }
        } catch (Exception e) {
            log.error("更新客户等级失败", e);
            return ApiResult.error(ResultCode.ERROR, "更新客户等级失败");
        }
    }
}